import { HTTP_REQUEST_URL, HEADER, TOKENNAME} from '@/config/app';
import { toLogin, checkLogin } from '../libs/login';
import store from '../store';


/**
 * 发送请求
 */
function baseRequest(url, method, data, {noAuth = false, noVerify = false})
{
  let Url = HTTP_REQUEST_URL, header = HEADER;
  
  if (!noAuth) {
    //登录过期自动登录
	if(!store.state.app.token && !checkLogin()){
		toLogin();
		return Promise.reject({msg:'没有登录账号，需要登录才能体验完整的功能。'});
	}
  }
  
  if (store.state.app.token) header[TOKENNAME] = store.state.app.token;
  if(method.toLowerCase()=='post'){
	// header['content-type']= 'application/x-www-form-urlencoded';
  }
  return new Promise((reslove, reject) => {
    uni.request({
      url: Url + '/api/webapp/' + url,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
        if (noVerify)
          reslove(res.data, res);
        else if (res.data.code == 200)
          reslove(res.data, res);
		else if (res.data.code == 90099)
          uni.showModal({
			...res.data.data,
			success(e) {
				if(e.confirm){
					if(res.data.data.path){						
						uni.navigateTo({
							url:res.data.data.path,
							fail(error) {
								console.log(error)
								uni.showToast({
									title:"跳转出错",
									icon:"none"
								})
							}
						})
					}
				}else{
					if(res.data.data.errorpath){
						uni.navigateTo({
							url:res.data.data.errorpath,
							fail(error) {
								console.log(error)
								uni.showToast({
									title:"跳转出错",
									icon:"none"
								})
							}
						})
					}
				}
			}
          })
        else if ([410000, 410001, 410002].indexOf(res.data.code) !== -1) {
		  toLogin();
          reject(res.data);
        } else{
			let errorMsg=res.data.msg?res.data.msg:res.data?res.data:"接口错误";
			uni.showModal({
				title:"提示",
						content:errorMsg,
						cancelText:"复制错误",
						confirmText:"好的",
						cancelColor:"#2979ff",
						confirmColor:"#666",
						showCancel:res.data.msg?false:true,
						success(e) {
							if(e.cancel){
								uni.setClipboardData({
									data: errorMsg,
									success: function () {
										console.log('success');
									}
								});
							}
						}
			})
			reject(res.data|| '系统错误');
		}
      },
      fail: (msg) => {
        reject('请求失败',msg);
      }
    })
  });
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;